package com.qyb.zx;

import com.google.zxing.*;
import com.google.zxing.Reader;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.GlobalHistogramBinarizer;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.GenericMultipleBarcodeReader;
import com.google.zxing.multi.MultipleBarcodeReader;

import com.google.zxing.qrcode.QRCodeReader;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.junit.Test;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 实现功能：
 * <p/>
 *
 * @author 秦有宝
 * @version 1.0.00
 */
public class QybZx {

    @Test
    public void pdfToImage1(){

        File file = new File("D:\\tt\\滴滴电子发票（史擘寅）.pdf");
        BufferedImage bufferedImage = null;
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                // 方式1,第二个参数是设置缩放比(即像素)
                bufferedImage = renderer.renderImageWithDPI(i, 300);
                bufferedImage = bufferedImage.getSubimage(0, 0, 500, 500);
                // 方式2,第二个参数是设置缩放比(即像素)
                //bufferedImage = renderer.renderImage(i, 300 / 72f, ImageType.GRAY);
//                ImageIO.write(bufferedImage, "PNG", new File("D:\\tt\\111.png"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        File outputfile = new File("D:\\saved.png");
        try {
            ImageIO.write(bufferedImage, "png", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //
       // BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);
        HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
        //乱码。
        // 解码设置编码方式为：utf-8，
        decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        //优化精度
        decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        //开启PURE_BARCODE模式。（这是解决我的方案，带图片LOGO的解码方案）
        //复杂模式，开启PURE_BARCODE模式
        //decodeHints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        Result result = null;
        try {
            result = new MultiFormatReader().decode(bitmap, decodeHints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        String s =  result.getText();
        System.out.println(s);
    }
    @Test
    public void javaTest(){
        String ss = "12,01,15,42";
        String[] s = ss.split(",");
        System.out.println(s);
        try {
            Date date = new SimpleDateFormat("yyyyMMdd").parse("20170105");
            System.out.println(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }


    @Test
    public void pdfToImage2(){

            // 待解析PDF
            File pdfFile = new File("D:\\tt\\7.pdf");
//            File pdfFile = new File("D:\\tt\\京东办公用品发票1.pdf");
            // 空白PDF
            // 空白PDF
//            File pdfFile_out = new File("/Users/xiaolong/Downloads/testout.pdf");

          PDDocument document = null;
           PDDocument document_out = new PDDocument();
        document_out.addPage(new PDPage());
            try {
                document = PDDocument.load(pdfFile);
//                document_out = PDDocument.load(pdfFile_out);
            } catch (IOException e) {
                e.printStackTrace();
            }

            int pages_size = document.getNumberOfPages();

            System.out.println("getAllPages==============="+pages_size);
            int j=0;

            for(int i=0;i<pages_size;i++) {
                PDPage page = document.getPage(i);
                PDPage page1 = document_out.getPage(0);
                PDResources resources = page.getResources();
                Iterable xobjects = resources.getXObjectNames();

                if (xobjects != null) {
                    Iterator imageIter = xobjects.iterator();
                    while (imageIter.hasNext()) {
                        COSName key = (COSName) imageIter.next();
                        if(resources.isImageXObject(key)){
                            try {
                                PDImageXObject image = (PDImageXObject) resources.getXObject(key);

                                // 方式一：将PDF文档中的图片 分别存到一个空白PDF中。
                                PDPageContentStream contentStream = new PDPageContentStream(document_out,page1, PDPageContentStream.AppendMode.APPEND,true);

                                float scale = 1f;
                                contentStream.drawImage(image, 20,20,image.getWidth()*scale,image.getHeight()*scale);
                                contentStream.close();
//                                document_out.save("/Users/xiaolong/Downloads/123"+j+".pdf");
//                                System.out.println(image.getSuffix() + ","+image.getHeight() +"," + image.getWidth());



                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            //image count
                            j++;
                        }
                    }
                }
            }

        BufferedImage bufferedImage = null;
        try {

            PDFRenderer renderer = new PDFRenderer(document_out);
            int pageCount = document_out.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                // 方式1,第二个参数是设置缩放比(即像素)
                //bufferedImage = renderer.renderImageWithDPI(i, 296);
                // 方式2,第二个参数是设置缩放比(即像素)
                bufferedImage = renderer.renderImage(i, 300 / 72f, ImageType.GRAY);
                ImageIO.write(bufferedImage, "PNG", new File("D:\\tt\\1001.png"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //
        // BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);
        HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
        decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = null;
        try {
            result = new MultiFormatReader().decode(bitmap, decodeHints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        String s =  result.getText();
        System.out.println(s);

    }

   /* @Test
    public void pdfToImage3(){

        File file = new File("D:\\tt\\7.pdf");
        BufferedImage bufferedImage = null;
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
            for (int i = 0; i < pageCount; i++) {
                // 方式1,第二个参数是设置缩放比(即像素)
                //bufferedImage = renderer.renderImageWithDPI(i, 296);
                // 方式2,第二个参数是设置缩放比(即像素)
//                bufferedImage = renderer.renderImage(i, 300 / 72f, ImageType.GRAY);
//                ImageIO.write(bufferedImage, "PNG", new File("D:\\tt\\111.png"));
                pdfPage2Img(page,saveFileName,imgType);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //
        // BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);
        HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
        decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = null;
        try {
            result = new MultiFormatReader().decode(bitmap, decodeHints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        String s =  result.getText();
        System.out.println(s);
    }*/





    @Test
    public void pdfToImage4(){

        File file = new File("D:\\tt\\床上用品.pdf");
        BufferedImage bufferedImage = null;
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
          //  for (int i = 0; i < pageCount; i++) {
                // 方式1,第二个参数是设置缩放比(即像素)
                bufferedImage = renderer.renderImageWithDPI(0, 200, ImageType.RGB);
//                bufferedImage = bufferedImage.getSubimage(0, 0, 500, 500);
                // 方式2,第二个参数是设置缩放比(即像素)
                //bufferedImage = renderer.renderImage(i, 300 / 72f, ImageType.GRAY);
                ImageIO.write(bufferedImage, "PNG", new File("D:\\tt\\床上用品.png"));
          //  }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //LuminanceSource source = new RGBLuminanceSource(bufferedImage.getWidth(),bufferedImage.getHeight(),bufferedImage.get);
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Collection<Result> results = new ArrayList<>(1);

        Map<DecodeHintType,Object> HINTS = new EnumMap<>(DecodeHintType.class);
        HINTS.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
        Map<DecodeHintType,Object> HINTS_PURE = new EnumMap<>(HINTS);
        HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);

    Reader reader = new QRCodeReader();
    ReaderException savedException = null;
    try {
        // Look for multiple barcodes
        MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
        Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS);
        System.out.println("1");
        if (theResults != null) {
            results.addAll(Arrays.asList(theResults));
        }
    } catch (ReaderException re) {
        savedException = re;
    }

//            if (results.isEmpty()) {
        try {
            // Try again with other binarizer
            BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result theResult = reader.decode(hybridBitmap, HINTS);
            System.out.println("2");
            if (theResult != null) {
                results.add(theResult);
            }
        } catch (ReaderException re) {
            savedException = re;
        }
//            }

//            if (results.isEmpty()) {
        try {
            // Look for pure barcode
            Result theResult = reader.decode(bitmap, HINTS_PURE);
            System.out.println("3");
            if (theResult != null) {
                results.add(theResult);
            }
        } catch (ReaderException re) {
            savedException = re;
        }
//            }

//            if (results.isEmpty()) {
        try {
            // Look for normal barcode in photo
            Result theResult = reader.decode(bitmap, HINTS);
            System.out.println("4");
            if (theResult != null) {
                results.add(theResult);
            }
        } catch (ReaderException re) {
            savedException = re;
        }
//            }








  /*      Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);
        HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
        //乱码。
        // 解码设置编码方式为：utf-8，
        decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        //优化精度
        decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        //开启PURE_BARCODE模式。（这是解决我的方案，带图片LOGO的解码方案）
        //复杂模式，开启PURE_BARCODE模式
        //decodeHints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        Result result = null;
        try {
            result = new MultiFormatReader().decode(bitmap, decodeHints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        String s =  result.getText();
        System.out.println(s);*/
    }

    @Test
    public void pdfToImage5(){

        File file = new File("D:\\tt\\电信电子发票201811121004.pdf");
        BufferedImage bufferedImage = null;
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            //  for (int i = 0; i < pageCount; i++) {
            // 方式1,第二个参数是设置缩放比(即像素)
            bufferedImage = renderer.renderImageWithDPI(0, 300);
//            bufferedImage = bufferedImage.getSubimage(0, 0, 500, 500);
            // 方式2,第二个参数是设置缩放比(即像素)
            //bufferedImage = renderer.renderImage(i, 300 / 72f, ImageType.GRAY);
            ImageIO.write(bufferedImage, "PNG", new File("D:\\tt\\112.png"));
            //  }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            //得到图片的像素
//            int[] pixels = new int[bufferedImage.getWidth() * bufferedImage.getHeight()];
            //
//            bufferedImage.getPixels(pixels, 0, bufferedImage.getWidth(), 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
            LuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);
            Binarizer binarizer = new GlobalHistogramBinarizer(luminanceSource);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
//            hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
            Result result = new QRCodeReader().decode(binaryBitmap, hints);
            System.out.println(result.getText());
        } catch (Exception e) {
            e.printStackTrace();

        }


    }


    @Test
    public void einvoiceRecognizeUtil(){
        // 建立当前目录中文件的File对象
        File fileDir = new File("D:\\tt\\qqq.pdf");
        // 取得代表目录中所有文件的File对象数组
        File[] files = fileDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            try {
                File file = files[i];
                InputStream in = new FileInputStream(file);
                String s = EinvoiceRecognizeUtil.recogonize(in);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void einvoiceRecognize(){
        // 建立当前目录中文件的File对象
        File file = new File("D:\\tt\\qqq.pdf");
        // 取得代表目录中所有文件的File对象数组
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            String s = EinvoiceRecognizeUtil.recogonize(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }





    }


}
